package com.atjinggu.jinggumail.search.test;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jingming
 * @Type SftpUtil.java
 * @Desc
 * @date 2021/1/11 22:22
 */
@Slf4j
public class SftpUtil {

    /**
     * 创建SFTP连接
     * @return
     * @throws Exception
     */
    private ChannelSftp createSftp() throws Exception {
        JSch jsch = new JSch();
        log.info("Try to connect sftp[" +"root" + "@" + "192.168.56.11" + "], use password[" + "vagrant" + "]");

        Session session = createSession(jsch, "192.168.56.11", "root", 22);
        session.setPassword("vagrant");
        session.connect(2000);

        log.info("Session connected to {}.", "192.168.56.11");

        Channel channel = session.openChannel("sftp");
        channel.connect(15000);

        log.info("Channel created to {}.", "192.168.56.11");

        return (ChannelSftp) channel;
    }

    private Session createSession(JSch jsch, String host, String username, Integer port) throws Exception {
        Session session = null;
        if (port <= 0) {
            session = jsch.getSession(username, host);
        } else {
            session = jsch.getSession(username, host, port);
        }

        if (session == null) {
            throw new Exception(host + " session is null");
        }

        session.setConfig("StrictHostKeyChecking", "no");
        return session;
    }



    public boolean downloadFile(String targetPath) throws Exception {
        ChannelSftp sftp = this.createSftp();
        OutputStream outputStream = null;
        try {
            sftp.cd("/tmp");
            log.info("Change path to {}", "/tmp");
//            File file = new File(targetPath.substring(targetPath.lastIndexOf("/") + 1));
            File file = new File(targetPath);
            if (file.exists()) {
                file.delete();
            }
            //创建新文件
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            sftp.get("test.txt", outputStream);
            log.info("Download file success. TargetPath: {}", targetPath);
            return true;
        } catch (Exception e) {
            log.error("Download file failure. TargetPath: {}", targetPath, e);
            return false;

        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            this.disconnect(sftp);
        }
    }

    /**
     * 关闭连接
     * @param sftp
     */
    private void disconnect(ChannelSftp sftp) {
        try {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                } else if (sftp.isClosed()) {
                    log.info("sftp is closed already");
                }
                if (null != sftp.getSession()) {
                    sftp.getSession().disconnect();
                }
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取.csv文件
     * @param path 文件路径
     * @return
     */
    public List<String> readFile(String path) {
        File file = new File(path);
        file.setReadable(true);//设置可读
        file.setWritable(true);//设置可写
        BufferedReader br = null;
        String line = "";
        String everyLine = "";
        List<String> list = new ArrayList<String>();
        try {
            br = new BufferedReader(new FileReader(file));
            while ((line=br.readLine())!=null){
                everyLine = line;
                list.add(everyLine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}